import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.stereotype.Component;

@Component
public class ZookeeperDistributedLock {

    private final CuratorFramework curatorFramework;

    public ZookeeperDistributedLock(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    /**
     * 尝试获取锁并执行任务
     *
     * @param lockPath 锁路径
     * @param task 任务
     * @throws Exception
     */
    public void executeWithLock(String lockPath, Runnable task) throws Exception {
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);
        try {
            lock.acquire();
            task.run();
        } finally {
            lock.release();
        }
    }
}
